package ld.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import ld.mapper.DeptMapper;
import ld.mapper.EmpMapper;
import ld.pojo.Emp;
import ld.pojo.EmpExample;
import ld.service.EmpService;
import ld.utils.PageResult;
import ld.vo.EmpVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Liudao
 * @Date: 2022-08-10-16:23
 * @Description:
 */
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Emp> findAll() {
        List<Emp> emps = empMapper.selectAll();
        for (Emp emp : emps) {
            emp.setDname(deptMapper.selectByPrimaryKey(emp.getDid()).getDname());
        }
        return emps;
    }

    @Override
    public PageResult<Emp> search(int page, int pagesize, EmpVo empVo) {
        //开始分页
        PageHelper.startPage(page,pagesize);
        //定义实例对象
        Example example = new Example(Emp.class);
        Example.Criteria criteria = example.createCriteria();
        //封装查询条件
        if (!StringUtils.isEmpty(empVo.getEname())){
            criteria.andLike("ename","%" + empVo.getEname() + "%");
        }
        if (!StringUtils.isEmpty(empVo.getCity())){
            criteria.andLike("city","%" + empVo.getCity() + "%");
        }
        if (empVo.getDid() != 0){
            criteria.andEqualTo("did",empVo.getDid());
        }
        //进行查询
        List<Emp> emps = empMapper.selectByExample(example);
        //给dname赋值
        for (Emp emp : emps) {
            emp.setDname(deptMapper.selectByPrimaryKey(emp.getDid()).getDname());
        }
        //转换为pageinfo
        PageInfo<Emp> empPageInfo = new PageInfo<>(emps);
        //返回pageresult
        return new PageResult<>(empPageInfo.getTotal(),empPageInfo.getList());
    }

    @Override
    public void add(Emp emp) {
        empMapper.insert(emp);
    }

    @Override
    public void update(Emp emp) {
        empMapper.updateByPrimaryKey(emp);
    }

    @Override
    public void delete(List<Integer> eids) {        //删除可以不用条件对象，用循环主键去删
        EmpExample empExample = new EmpExample();
        EmpExample.Criteria criteria = empExample.createCriteria();
//        List<Integer> collect = eids.stream().map(Integer::valueOf).collect(Collectors.toList());如果传入的是List<String>需要转换
        criteria.andEidIn(eids);
        empMapper.deleteByExample(empExample);
    }


}
